package com.prdiot.poetry.controller;

import com.prdiot.poetry.dao.PoemsRepository;
import com.prdiot.poetry.domains.Poems;
import com.prdiot.poetry.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Controller
public class SearchController {

    @Autowired
    SearchService searchService;

    @Autowired
    PoemsRepository poemsRepository;

    @Autowired
    PoemsService poemsService;

    @Autowired
    TagsService tagsService;

    @Autowired
    MingjuService mingjuService;

    @Autowired
    ChengyuService chengyuService;

    //搜索功能
    @GetMapping("/search")
    public String search(Model model, @RequestParam(value="searchVal",required=false) String searchVal,
                         @RequestParam(value="searchType",required=false,defaultValue="poem") String searchType,
                         @RequestParam(value="page",required=false,defaultValue="1") int page){

        if (StringUtils.isEmpty(page)){
            page = 1;
        }

        if (StringUtils.isEmpty(searchType)){
            searchType = "poem";
        }

        Map<String, Object> mapResult = searchService.search(page,searchVal,searchType);
        model.addAttribute("dataList", mapResult.get("list"));
        model.addAttribute("page", Integer.valueOf(page));
        model.addAttribute("pageCount",  Integer.valueOf(mapResult.get("pageCount").toString()));
        model.addAttribute("searchType", searchType);
        model.addAttribute("searchVal", searchVal);
        if (searchType.equalsIgnoreCase("author")){
            model.addAttribute("extPomesData", mapResult.get("extPomesData"));
        }

        List<Poems> list = poemsService.getRandPoetry();

        model.addAttribute("poemsList", list);
        model.addAttribute("tagList",tagsService.getTagsOrderByPoemCount(100));
        model.addAttribute("themeList",mingjuService.getMingjuTheme());
        model.addAttribute("mingjuList",mingjuService.getRandMingju());
        model.addAttribute("chengyuList",chengyuService.getRandPoetry());

        return "search";
    }



}
